using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using MimeCloud.AssetManagement.ProviderServices.Repository;

namespace MimeCloud.AssetManagement.Editor.Saving
{
    public abstract class SaveManagerBase
    {
        public void BeginSaveAsync(AssetSaveArguments args, ProgressChangedEventHandler progressHandler)
        {
            saveWorker.WorkerSupportsCancellation = true;
            saveWorker.WorkerReportsProgress = true;
            saveWorker.ProgressChanged += ((sender, e) =>
                                               {
                                                   if (e.UserState is AssetSaveProgressReport)
                                                       OnProgressChanged(e.UserState as AssetSaveProgressReport);
                                               });
            saveWorker.DoWork += ((sender, e) => ExecuteSaveTasks(e.Argument as AssetSaveArguments, e));
            saveWorker.RunWorkerCompleted += ((sender, e) =>
                                                  {
                                                      if (e.Result is AssetSaveResult)
                                                          OnSaveComplete(e.Result as AssetSaveResult);
                                                  });
        }

        public delegate void SaveProgressChangedEventHandler(AssetSaveProgressReport progressReport);
        public delegate void SaveCompleteEventHandler(AssetSaveResult result);
        public event SaveProgressChangedEventHandler SaveProgressChanged;
        public event SaveCompleteEventHandler SaveComplete;

        private void OnProgressChanged(AssetSaveProgressReport report)
        {
            if (SaveProgressChanged != null)
                SaveProgressChanged(report);
        }
        private void OnSaveComplete(AssetSaveResult result)
        {
            if (SaveComplete != null)
                SaveComplete(result);
        }

        protected BackgroundWorker saveWorker = new BackgroundWorker();
        public void AbortOperation()
        {
            saveWorker.CancelAsync();
        }
        protected void ReportProgress(AssetSaveProgressReport progressReport)
        {
           if (saveWorker.WorkerReportsProgress)
            saveWorker.ReportProgress(0, progressReport);
        }
        public AssetSaveResult Save(AssetSaveArguments args)
        {
            return ExecuteSaveTasks(args, new DoWorkEventArgs(null));
        }
        protected abstract AssetSaveResult ExecuteSaveTasks(AssetSaveArguments args, DoWorkEventArgs e);
    }
}
